/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metro.jme.lottery.sound;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;
import metro.jme.lottery.graphics.screens.TrackSelecter;
import metro.jme.lottery.main.LotteryMIDlet;

/**
 * This class provides a Midi Player than can be used by the MIDlet to
 * play midi files.
 * @author pierre
 */
public class MidiPlayer implements Runnable {

	private Player m_player;
	private LotteryMIDlet m_MIDlet;
	private VolumeControl m_volumeControl;
	public int m_volume;
	public boolean m_isRunning;
	private static final String FOLDER = "/sounds";

	public MidiPlayer(LotteryMIDlet m) {
		m_MIDlet = m;
		m_volume = 50;
		m_isRunning = false;
	}

	/**
	 * Runnable method
	 */
	public void run() {
		m_isRunning = true;
		try {
			InputStream is = getClass().getResourceAsStream(FOLDER + "/" + TrackSelecter.getCURRENT_TRACK() + ".mid");
			m_player = Manager.createPlayer(is, "audio/midi");
			m_player.realize();

			m_volumeControl = (VolumeControl) m_player.getControl("VolumeControl");
			if (m_volumeControl != null) {
				m_volumeControl.setLevel(20);
				m_volume = 20;
				System.out.println("vol");
			}

			m_player.prefetch();
			m_player.start();
		} catch (MediaException me) {
			me.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		m_isRunning = false;
	}

	/**
	 * Stop the player
	 */
	public void pausePlayer() {
		if (m_player != null) {
			m_player.close();
		}
		m_isRunning = false;
	}

	public void volumeUp() {
		if (m_volumeControl != null) {
			m_volumeControl.setLevel(m_volumeControl.getLevel() + 10);
			System.out.println("vol up");
			m_volume = m_volumeControl.getLevel();
		}
	}

	public void volumeDown() {
		if (m_volumeControl != null) {
			m_volumeControl.setLevel(m_volumeControl.getLevel() - 10);
			System.out.println("vol down");
			m_volume = m_volumeControl.getLevel();
		}
	}

	public boolean isRunning() {
		return m_isRunning;
	}
}
